package com.aat.dxfy.lucene.test;

// 主类  
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.NumericDocValuesField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TermRangeQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.LockObtainFailedException;
import org.apache.lucene.store.RAMDirectory;
import org.apache.lucene.util.BytesRef;

public class Search {
	private String[] ids = { "1", "2", "3", "4", "5", "6" };
	private String[] emails = { "aa@aa.com", "bb@bb.com", "cc@cc.com", "dd@dd.com", "ee@ee.com", "ff@ff.com" };
	private String[] contents = { "i like  gdsfgfds", "i like fsdfs", "i like fdsfsd", "i like fdsfsd",
			"i like like fdfs", "i like like like fsefsdfg" };
	private int[] attachs = { 1, 2, 3, 4, 5, 6 };
	private String[] names = { "liwu", "zhangsan", "xiaoqinag", "laona", "dabao", "lisi" };
	private IndexWriter writer = null;
	private Date[] dates = null;
	private Map<String, Float> scores = new HashMap<String, Float>();
	private Directory directory = null;
	private IndexReader reader = null;

	public Search() {
		directory = new RAMDirectory();
		setDate();
		index();
	}

	// 建立索引
	public void index()  
    {  
        Document document=null;  
         try {  
            writer=new IndexWriter(directory, new IndexWriterConfig(new StandardAnalyzer()));  
            writer.deleteAll();//更新索引  
            for(int i=0;i<ids.length;i++)  
            {  
                document=new Document();  
                document.add(new Field("id", ids[i],TextField.TYPE_NOT_STORED));  
                document.add(new Field("email",emails[i], TextField.TYPE_STORED));  
                document.add(new Field("content", contents[i], TextField.TYPE_STORED)); 
                
                document.add(new Field("name",names[i],  TextField.TYPE_NOT_STORED));  
                //为数字添加索引  
                document.add(new NumericDocValuesField("attach",attachs[i]));  
                //为日期添加索引  
                document.add(new NumericDocValuesField("date", dates[i].getTime()));//记住要getTime  
                          
                  
                String str=emails[i].substring(emails[i].lastIndexOf("@")+1);  
                //System.out.println(str);  
                if(scores.containsKey(str))  
                {  
                    //document.setBoost(scores.get(str));  
                }else{  
                	//document.setBoost(0.5f);  
                }  
                writer.addDocument(document);  
                writer.commit();//提交writer  
            }  
        } catch (CorruptIndexException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        } catch (LockObtainFailedException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        } catch (IOException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        }  
        finally{  
            try {  
                writer.close();  
            } catch (CorruptIndexException e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace();  
            } catch (IOException e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace();  
            }  
        }  
    }

	// 获取searcher
	public IndexSearcher getSearcher() {
		try {
			reader = DirectoryReader.open(directory);
			return new IndexSearcher(reader);
		} catch (CorruptIndexException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	// 精确查找
	public void searchByTerm(String field, String name, int num) {
		try {
			IndexSearcher searcher = getSearcher();
			Query query = new TermQuery(new Term(field, name));
			TopDocs tds = searcher.search(query, num);
			System.out.println("一共查询了：" + tds.totalHits);
			for (ScoreDoc sd : tds.scoreDocs) {
				Document doc = searcher.doc(sd.doc);
				System.out.println(doc.get("id") + "-->" + doc.get("name") + ".." + "[" + doc.get("email") + "]" + "("
						+ doc.get("content") + ")" + "-->" + doc.get("attach") + ".." + doc.get("date"));
			}

			//searcher.close();
		} catch (CorruptIndexException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	// 范围查询
	public void searchByTermRange(String field, String start, String end, int num) {

		try {
			IndexSearcher searcher = getSearcher();
			Query query = new TermRangeQuery(field, new BytesRef(start), new BytesRef(end), true, true);
			TopDocs tds = searcher.search(query, num);
			System.out.println("一共查询了：" + tds.totalHits);
			for (ScoreDoc sd : tds.scoreDocs) {
				Document doc = searcher.doc(sd.doc);
				System.out.println(doc.get("id") + "-->" + doc.get("name") + ".." + "[" + doc.get("email") + "]" + "("
						+ doc.get("content") + ")" + "-->" + doc.get("attach") + ".." + doc.get("date"));
			}
			//searcher.close();
		} catch (CorruptIndexException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	// 范围查询
	@SuppressWarnings("deprecation")
	public void searchByNumRange(String field, int start, int end, int num) {

		try {
			IndexSearcher searcher = getSearcher();
			Query query = org.apache.lucene.search.LegacyNumericRangeQuery.newIntRange(field, start, end, true, true);
			TopDocs tds = searcher.search(query, num);
			System.out.println("一共查询了：" + tds.totalHits);
			for (ScoreDoc sd : tds.scoreDocs) {
				Document doc = searcher.doc(sd.doc);
				System.out.println(doc.get("id") + "-->" + doc.get("name") + ".." + "[" + doc.get("email") + "]" + "("
						+ doc.get("content") + ")" + "-->" + doc.get("attach") + ".." + doc.get("date"));
			}
			//searcher.close();
		} catch (CorruptIndexException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	// 创建日期
	public void setDate() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-kk");
		try {
			dates = new Date[ids.length];
			dates[0] = sdf.parse("2010-08-17");
			dates[1] = sdf.parse("2011-02-17");
			dates[2] = sdf.parse("2012-03-17");
			dates[3] = sdf.parse("2011-04-17");
			dates[4] = sdf.parse("2012-05-17");
			dates[5] = sdf.parse("2011-07-17");
		} catch (Exception e) {
			e.printStackTrace();
			// TODO: handle exception
		}
	}
}